(function($) {
	var _lookup = {
		currentGroup : "",
		suffix : false,
		$target : null
	};
	var _util = {
		_lookupPrefix : function(key) {
			var strDot = _lookup.currentGroup ? "." : "";
			return _lookup.currentGroup + strDot + key;
		},
		lookupPk : function(key) {
			return this._lookupPrefix(key) + (_lookup.suffix ? "[]" : "");
		},
		lookupField : function(key) {
			return "cybertron." + this.lookupPk(key);
		}
	};

	var jUpload = $('<div style="width:113px;height:52px;">图片文件:<input id="xheFile" type="file" /></div>');
	var jUploadTip = $('<div style="padding:22px 0;text-align:center;line-height:30px;">文件上传中，请稍候……<br /></div>');
	var jProgress = $('<div class="cybertronProgress"><div><span>0%</span></div></div>');
	var bShowModal = false, layerShadow = 20, onModalRemove, isIE = $.browser.msie, browerVer = $.browser.msie, jHideSelect;

	var defUploadifyOpts = {
		fileTypeDesc : 'jpg,jpeg,bmp',
		fileTypeExts : '*.jpeg;*.jpg;*.bmp;',
		multi : false,
		auto : true,
		fileSizeLimit : "1MB",
		swf : base + "/template/common/uploadify/scripts/uploadify.swf",
		buttonImage : base + '/template/common/uploadify/img/add.jpg',
		uploader : base + "/upload!doUpload.action;jsessionid=" + sessionId,
		buttonClass : "cybertron-uploadify-button",
		height : 28,
		width : 102,
		queueID : true,
		onUploadSuccess : function(file, data, response) {
			DWZ.debug("uploadSuccess: " + response);
		},
		onUploadProgress : function(file, bytesUploaded, bytesTotal,
				totalBytesUploaded, totalBytesTotal) {
			var sPercent = Math.round(bytesUploaded / bytesTotal * 100) + '%';
			$('div', jProgress).css('width', sPercent);
			$('span', jProgress).text(
					sPercent + ' ( ' + formatBytes(bytesUploaded) + ' / '
							+ formatBytes(totalBytesTotal) + ' )');

		},
		onUploadComplete : function() {
			removeModal();
		},
		onUploadStart : function(file) {
			var jUploadContent = $("<div></div>");
			jUploadContent.append(jUploadTip);
			jUploadContent.append(jProgress);
			showModal('正在上传请稍后', jUploadContent, 320, 150);
		},
		onUploadError : uploadifyError
	};
	function formatBytes(bytes) {
		var s = [ 'Byte', 'KB', 'MB', 'GB', 'TB', 'PB' ];
		var e = Math.floor(Math.log(bytes) / Math.log(1024));
		return (bytes / Math.pow(1024, Math.floor(e))).toFixed(2) + s[e];
	}
	function showModal(title, content, w, h, onRemove) {
		if (bShowModal)
			return false;// 只能弹出一个模式窗口
		bShowPanel = false;// 防止按钮面板被关闭
		jModal = $(
				'<div class="cybertronModal" style="width:'
						+ (w - 1)
						+ 'px;height:'
						+ h
						+ 'px;margin-left:-'
						+ Math.ceil(w / 2)
						+ 'px;'
						+ (isIE && browerVer < 7.0 ? '' : 'margin-top:-'
								+ Math.ceil(h / 2) + 'px')
						+ '">'
						+ ('<div class="cybertronModalTitle"><span class="cybertronModalClose" title="关闭 (Esc)" tabindex="0" role="button"></span>'
								+ title + '</div>')
						+ '<div class="cybertronModalContent"></div></div>')
				.appendTo('body');
		jOverlay = $('<div class="cybertronModalOverlay"></div>').appendTo(
				'body');
		if (layerShadow > 0)
			jModalShadow = $(
					'<div class="cybertronModalShadow" style="width:'
							+ jModal.outerWidth()
							+ 'px;height:'
							+ jModal.outerHeight()
							+ 'px;margin-left:-'
							+ (Math.ceil(w / 2) - layerShadow - 2)
							+ 'px;'
							+ (isIE && browerVer < 7.0 ? '' : 'margin-top:-'
									+ (Math.ceil(h / 2) - layerShadow - 2)
									+ 'px') + '"></div>').appendTo('body');

		$('.cybertronModalContent', jModal).css('height',
				h - ($('.cybertronModalTitle').outerHeight())).html(content);

		if (isIE && browerVer === 6.0)
			jHideSelect = $('select:visible').css('visibility', 'hidden');// 隐藏覆盖的select
		$('.cybertronModalClose', jModal).click(removeModal);
		jOverlay.show();
		if (layerShadow > 0)
			jModalShadow.show();
		jModal.show();
		setTimeout(function() {
			jModal.find('a,input[type=text],textarea').filter(':visible')
					.filter(function() {
						return $(this).css('visibility') !== 'hidden';
					}).eq(0).focus();
		}, 10);// 定位首个可见输入表单项,延迟解决opera无法设置焦点
		bShowModal = true;
		onModalRemove = onRemove;
	}
	function removeModal() {
		if (jHideSelect)
			jHideSelect.css('visibility', 'visible');
		jModal.html('').remove();
		if (layerShadow > 0)
			jModalShadow.remove();
		jOverlay.remove();
		if (onModalRemove)
			onModalRemove();
		bShowModal = false;
	}
	$.cybertron = {
		bringBackSuggest : function(args) {
			var $box = _lookup['$target'].parents(".unitBox:first");
			$box.find(":input").each(function() {
				var $input = $(this), inputName = $input.attr("name");
				for ( var key in args) {
					var name = _util.lookupPk(key) || _util.lookupField(key);
					if (name == inputName) {
						$input.val(args[key]);
						break;
					}
				}
			});
		},
		autocomplete : function(item) {
			item.each(function() {
				var $input = $(this);
				var autocompleteOpts = DWZ.jsonEval($input
						.attr("autocompleteOpts"));
				var autocompleteValue = autocompleteOpts.autocomplteValue
						|| "name" || "label";
				var options = $input.metadata();
				var defaultOptions = {
					matchContains : true,
					dataType : "json",
					mustmatch : true,
					type : "GET",
					max : 20,
					selectFirst : true,
					parse : function(data) {
						return $.map(data, function(row) {
							return {
								data : row,
								value : row[autocompleteValue],
								result : row[autocompleteValue]
							};
						});
					},
					formatItem : function(row, i, max) {
						return row[autocompleteValue];
					},
					formatMatch : function(row, i, max) {
						return row[autocompleteValue];
					}
				};
				options = $.extend(defaultOptions, autocompleteOpts);
				var isUrl = typeof options.urlOrData == "string";
				$input.focus(function(event) {
					if (!isUrl) {
						return false;
					}
					var url = unescape(options.urlOrData).replaceTmById(
							$(event.target).parents(".unitBox:first"));
					if (!url.isFinishedTm()) {
						alertMsg.error($input.attr("warn")
								|| DWZ.msg("alertSelectMsg"));
						return false;
					}
					_lookup = $.extend(_lookup, {
						currentGroup : $input.attr("lookupGroup") || "",
						suffix : $input.attr("suffix") || false,
						$target : $input
					});
					options.url = url;
					$input.setOptions(options);
					$input.flushCache();
				});
				$input.autocomplete(options.urlOrData, options);
				$input.result(function(event, data, formatted) {
					var $this = $(this);
					var lookupAttrs = DWZ.jsonEval($this.attr("lookupAttrs"));
					for ( var key in lookupAttrs) {
						lookupAttrs[key] = data[lookupAttrs[key]];
					}
					$.cybertron.bringBackSuggest(lookupAttrs);
				});
			});
		},
		xhEditor : function(args) {
			var xheUploadOpts = {
				fileObjName : "filedata",
				width : 102,
				height : 24,
				uploader : base + "/upload!doXheditorUpload.action;jsessionid="
						+ sessionId,
				fileSizeLimit : "2MB"
			};
			var plugins = {
				Pic : {
					c : 'xheIcon xheBtnImg',
					t : '图片上传 (Ctrl+1)',
					s : 'ctrl+1',
					h : 1,
					e : function() {
						var _this = this;
						var jFile = $("#xheFile", jUpload);

						_this.saveBookmark();
						_this.showDialog(jUpload);

						xheUploadOpts.onUploadStart = function(file) {
							var jUploadContent = $("<div></div>");
							jUploadContent.append(jUploadTip);
							jUploadContent.append(jProgress);
							_this
									.showModal('正在上传请稍后', jUploadContent, 320,
											150);
						};
						xheUploadOpts.onUploadComplete = function() {
							_this.removeModal();
							_this.hidePanel();
						};
						xheUploadOpts.onUploadSuccess = function(file, data,
								response) {
							if (!response) {
								return;
							}
							data = eval("(" + data + ")");
							if (data.err === undefined) {
								alert(data.err);
								return;
							}
							console.log();
							_this.loadBookmark();
							_this.pasteHTML("<img src=" + data.url + " />");
						};
						var opts = $
								.extend({}, defUploadifyOpts, xheUploadOpts);
						jFile.uploadify(opts);
					}
				}
			};
			var xhTools = 'Cut,Copy,Paste,|,Pastetext,Blocktag,Fontface,FontSize,Bold,Italic,Underline,Strikethrough,FontColor,BackColor,SelectAll,'
					+ 'Removeformat,Align,List,Outdent,Indent,Link,Unlink,Anchor,Hr,'
					+ '|,Table,Pic,Fullscreen';
			// xheditor html文本编辑器
			args.each(function() {
				var $this = $(this);
				var options = eval("(" + $this.attr("xheditorOptions") + ")");
				var defOptions = {
					tools : xhTools,
					skin : 'default',
					upImgExt : "jpg,jpeg,bmp",
					upImgUrl : base + '/upload!doXheditorUpload.action',
					cleanPaste : 2,
					plugins : plugins
				};
				var opts = $.extend({}, defOptions, options);
				$this.xheditor(opts);
			});
		},
		uploadify : function(args) {
			args.each(function() {
				var $this = $(this);
				var uploadifyOpts = DWZ.jsonEval($this.attr("uploadifyOpts"));
				var fileObjName = $this.attr("name") || "filedata";
				if (uploadifyOpts) {
					uploadifyOpts.fileObjName = fileObjName;
				}
				var opts = $.extend({}, defUploadifyOpts, uploadifyOpts);
				$this.uploadify(opts);
			});
		}
	};
})(jQuery);